package com.currency.mall.ui.main;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.currency.mall.R;
import com.currency.mall.adapter.OptionalAdapter;
import com.currency.mall.adapter.ShareIndexAdapter;
import com.currency.mall.di.component.DaggerInquiryComponent;
import com.currency.mall.di.modlue.InquiryModule;
import com.currency.mall.entity.SecurityBean;
import com.currency.mall.entity.SharesBean;
import com.currency.mall.ui.login.LoginActivity;
import com.currency.mall.ui.main.inquiry.InquiryContract;
import com.currency.mall.ui.main.inquiry.InquiryDetailsActicity;
import com.currency.mall.ui.main.inquiry.InquiryPresent;
import com.currency.mall.util.Util;
import com.currency.mall.widget.HorizontalPageLayoutManager;
import com.mifengs.commonbase.base.BaseFragment;
import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.commonbase.util.StatusBarCompat;
import com.mifengs.commonbase.util.StatusBarUtils;
import com.mifengs.commonbase.util.ToastUitl;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/12/4.
 */

public class InquiryFragment extends BaseFragment<InquiryPresent> implements InquiryContract.View {

    @BindView(R.id.rv_inquiryList)
    RecyclerView rvInquiryList;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    Unbinder unbinder;
    @BindView(R.id.rv_share_index)
    RecyclerView rvShareIndex;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.ll_title_view)
    LinearLayout llTitleView;
    private OptionalAdapter mOptionalAdapter;
    private ShareIndexAdapter mShareIndexAdapter;
    private int mCurrentPage;
    List<SharesBean.SharesInfo> sharesInfoList;
    String strId[];
    private ScheduledExecutorService service;
    private boolean isSlide = false;
    private View headerView;

    public InquiryFragment() {
    }

    public static InquiryFragment newInstance() {
        InquiryFragment fragment = new InquiryFragment();
        return fragment;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View mView = inflater.inflate(R.layout.fragment_inquiry, container, false);
        unbinder = ButterKnife.bind(this, mView);
        StatusBarCompat.setStatusBarColor(getActivity(), ContextCompat.getColor(getContext(), R.color.title_color));
        StatusBarUtils.StatusBarLightMode(getActivity());
        init();
        return mView;
    }

    @Override
    public void initInjector() {
        DaggerInquiryComponent.builder()
                .inquiryModule(new InquiryModule(this))
                .build()
                .inject(this);
    }

    public void reloadInquiry() {
        init();
    }

    private void init() {
        if(rvInquiryList !=null) {
            sharesInfoList = new ArrayList<>();
            mCurrentPage = 1;
            rvInquiryList.setLayoutManager(new LinearLayoutManager(getContext()));
            rvInquiryList.setNestedScrollingEnabled(false);
            mOptionalAdapter = new OptionalAdapter(null, getContext());
            headerView = getLayoutInflater().inflate(R.layout.header_optional, null);
            headerView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            mOptionalAdapter.addHeaderView(headerView);
//        mOptionalAdapter.openLoadAnimation();
            refreshLayout.setEnableLoadMore(true);
            refreshLayout.setEnableRefresh(true);
            rvInquiryList.setAdapter(mOptionalAdapter);
            refreshLayout.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                    if (refreshLayout != null) {
                        mCurrentPage = 1;
                        Refresh();
                    }
                }
            });
            HorizontalPageLayoutManager horizontalPageLayoutManager = new HorizontalPageLayoutManager(1, 3);
            rvShareIndex.setLayoutManager(horizontalPageLayoutManager);
            rvShareIndex.setNestedScrollingEnabled(false);
            mShareIndexAdapter = new ShareIndexAdapter(null, getContext());
            rvShareIndex.setAdapter(mShareIndexAdapter);
            mOptionalAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    SharesBean.SharesInfo sharesInfo = sharesInfoList.get(position);
                    if (view.getId() == R.id.ll_collect) {
                        if (PreferenceUtils.getLoginStatus()) {
                            if (Util.useList(strId, sharesInfo.getId())) {
                                mPresenter.cancelCollectShares(sharesInfo.getId());
                            } else {
                                mPresenter.collectSharesInfo(sharesInfo.getId());
                            }
                        } else {
                            toLogin();
                        }

                    } else {
                        Intent intent = new Intent(getContext(), InquiryDetailsActicity.class);
                        startActivity(intent);
                    }
                }
            });

            mOptionalAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    SharesBean.SharesInfo sharesInfo = sharesInfoList.get(position);
                    Intent intent = new Intent(getContext(), InquiryDetailsActicity.class);
                    intent.putExtra("sharesInfo", sharesInfo);
                    startActivity(intent);
                }
            });

            scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
                @Override
                public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX,
                                           int oldScrollY) {
                    boolean localVisibleRect = isVisibleLocal(headerView);
                    if (localVisibleRect) {
                        llTitleView.setVisibility(View.GONE);
                    } else {
                        llTitleView.setVisibility(View.VISIBLE);
                    }

                    //判断是否滑到的底部
                    if (scrollY == (v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight())) {
                        onLoadMoreRequested();
                    } else {
                        isSlide = true;
                    }
                }
            });
            scrollView.setOnTouchListener(new View.OnTouchListener() {

                private int lastY = 0;
                private int touchEventId = -9983761;
                Handler handler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        View scroller = (View) msg.obj;
                        if (msg.what == touchEventId) {
                            if (lastY == scroller.getScrollY()) {
                                isSlide = false;
                            } else {
                                handler.sendMessageDelayed(handler.obtainMessage(touchEventId, scroller), 2);
                                lastY = scroller.getScrollY();
                            }
                        }
                    }
                };

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        handler.sendMessageDelayed(handler.obtainMessage(touchEventId, v), 2);
                    }
                    return false;

                }
            });
////
            service = Executors.newScheduledThreadPool(1);
            service.scheduleAtFixedRate(new VisibleScheduledExecutor(), 10, 5, TimeUnit.SECONDS);

            mPresenter.securityInfo();
            if (PreferenceUtils.getLoginStatus()) {
                mPresenter.getCollectSharesId(false, false);
            } else {
                strId = new String[0];
                mPresenter.getBondInfo(mCurrentPage, false);
            }
        }
    }

    //当 View 有一点点不可见时立即返回false!
    public static boolean isVisibleLocal(View target) {
        Rect rect = new Rect();
        target.getLocalVisibleRect(rect);
        return rect.top == 0;
    }

    private void Refresh() {
        mPresenter.securityInfo();
        if (PreferenceUtils.getLoginStatus()) {
            mPresenter.getCollectSharesId(false, true);
        } else {
            mPresenter.getBondInfo(mCurrentPage, true);
        }
    }

    Handler mHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (!isSlide)
                        Refresh();
                    break;
            }
        }
    };

    @OnClick(R.id.tv_search)
    public void onViewClicked() {
        toSearch();
    }


    class VisibleScheduledExecutor implements Runnable {

        @Override
        public void run() {
            Message msg = new Message();
            msg.what = 1;
            mHandle.sendMessage(msg);
        }
    }

    private void toSearch() {
        startActivity(new Intent(getContext(), SearchActivity.class));
    }

    public void toLogin() {
        Intent intent = new Intent(getContext(), LoginActivity.class);
        startActivity(intent);
    }

    @Override
    public void setSharesData(final List<SharesBean.SharesInfo> sharesInfos, final boolean isLoadOver, boolean isTimer) {
        mOptionalAdapter.setCollectShareId(strId);
        if (isLoadOver) {
            if (isTimer) {
                if (!isSlide) {
                    sharesInfoList.clear();
                    sharesInfoList.addAll(sharesInfos);
                    mOptionalAdapter.setNewData(sharesInfos);
                }
            } else {
                sharesInfoList.addAll(sharesInfos);
                mOptionalAdapter.addData(sharesInfos);
            }

        } else {
            sharesInfoList = sharesInfos;
            mOptionalAdapter.setNewData(sharesInfos);
        }
    }

    @Override
    public void setSecurityData(List<SecurityBean.SecurityInfo> securityInfos) {
        mShareIndexAdapter.setNewData(securityInfos);
    }

    public void finishRefresh() {
        if (refreshLayout != null)
            refreshLayout.finishRefresh();

    }

    @Override
    public void collectSharesId(String str[], boolean collect, boolean isTimer) {
        strId = str;
        if (collect) {
            mOptionalAdapter.setCollectShareId(strId);
            mOptionalAdapter.setNewData(sharesInfoList);
        } else {
            mPresenter.getBondInfo(mCurrentPage, isTimer);
        }

    }

    @Override
    public void refresh() {
        mPresenter.getCollectSharesId(true, false);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        shutDownService();
    }

    private void shutDownService() {
        if (service != null) {
            try {
                service.shutdown();
                if (!service.awaitTermination(1, TimeUnit.MILLISECONDS)) {
                    service.shutdownNow();
                }
            } catch (Exception exception) {
                service.shutdownNow();
            }
        }
    }


    public void onLoadMoreRequested() {
        mCurrentPage++;
        mPresenter.getBondInfo(mCurrentPage, false);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            shutDownService();
        } else {
            service = Executors.newScheduledThreadPool(1);
            service.scheduleAtFixedRate(new VisibleScheduledExecutor(), 10, 5, TimeUnit.SECONDS);
        }
    }
}
